
package biblio.util;


import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import biblio.util.interfaces.RegexContainer;


/**
 * Default implementation of {@link tryton.interfaces.RegexContainer}.
 * 
 * 2011-10-15
 * @author mephisto
 */
public class RegexContainerImpl implements RegexContainer
{
    /**
     * Default constructor which initializes containter with map of regex given 
     * as an argument.
     * 
     * @param regexColl to set the collection of regular expressions
     */
    public RegexContainerImpl(Map<String,String> regexColl)
    {
        init(regexColl);
    }
    
    @Override
    public void init(Map<String,String> regexColl)
    {
        regexMap = null;
        regexMap = new HashMap<String, Pattern>(regexColl.size());

        for(String  it : regexColl.keySet())
        {
            try
            {
                regexMap.put(it, Pattern.compile(regexColl.get(it)));
            }
            catch(PatternSyntaxException e)
            {
                org.apache.log4j.Logger.getLogger(getClass()).warn(
                        "Syntax of regex invalid. Regex " + it +
                        "was not added to container", e);
            }
        }
    }

    @Override
    public void clear()
    {
        regexMap.clear();
    }

    @Override
    public boolean containsRegexName(String regexName)
    {
        return regexMap.containsKey(regexName);
    }

    @Override
    public boolean containsRegex(String regex)
    {
        return regexMap.containsValue(Pattern.compile(regex));
    }

    @Override
    public Pattern getPattern(String regexName)
    {
        return regexMap.get(regexName);
    }

    @Override
    public String getRegex(String regexName)
    {
        return regexMap.get(regexName).pattern();
    }

    @Override
    public boolean isEmpty()
    {
        return regexMap.isEmpty();
    }

    @Override
    public Set<String> regexNameSet()
    {
        return regexMap.keySet();
    }

    @Override
    public Pattern add(String regexName, String regex)
    {
        return regexMap.put(regexName, Pattern.compile(regex));
    }

    @Override
    public Pattern remove(String regexName)
    {
        return regexMap.remove(regexName);
    }

    @Override
    public int size()
    {
        return regexMap.size();
    }

    @Override
    public Collection<Pattern> getPatterns()
    {
        return regexMap.values();
    }


    private Map<String, Pattern> regexMap = null;
}
